package com.qst0916_3.dao.impl;

import com.qst0916_3.dao.UserDao;
import com.qst0916_3.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;


import java.util.List;

@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private DataSourceTransactionManager txManager;

    @Override
    public int insert(User user) {

        String sql="insert into user values(?,?,?)";
        Object param[]={user.getId(),user.getUserName(),user.getUsePsw()};
        return jdbcTemplate.update(sql,param);
    }

    @Override
    public int deleteById(int id) {
        String sql="delete from user where id=?";

        return jdbcTemplate.update(sql,id);
    }

    @Override
    public List<User> getAllUser() {
        return null;
    }

    @Override
    public int insert2(User u1, User u2) {
        int result=0;
        String sql="insert into user values(?,?,?)";
        TransactionDefinition tf=new DefaultTransactionDefinition();
        TransactionStatus status=txManager.getTransaction(tf);
        try {
            Object param[] = {u1.getId(), u2.getUserName(), u2.getUsePsw()};
            Object param1[] = {u2.getId(), u2.getUserName(), u2.getUsePsw()};
            result = jdbcTemplate.update(sql, param);
            result += jdbcTemplate.update(sql, param1);
            txManager.commit(status);
        }catch (Exception e){
            result=0;
            txManager.rollback(status);
        }
        return result;
    }
}
